package com.lcy.redis.redistest;

import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class RedisTestApplication {

    @Autowired
    private RedissonClient redissonClient;

    public static void main(String[] args) {
        SpringApplication.run(RedisTestApplication.class, args);
    }


    @RequestMapping("/set")
    public String test(String key, String value) {
        RBucket<String> bucket = redissonClient.getBucket(key);
        bucket.getAndSet(value);
        return "success";
    }

    @RequestMapping("/test-lock")
    public String lock(String key) throws InterruptedException {
        if (StringUtils.isEmpty(key)) {
            return "key can not empty";
        }
        redissonClient.getReadWriteLock("");
        RSemaphore rSemaphore = redissonClient.getSemaphore(key);
        rSemaphore.acquireAsync();
        rSemaphore.acquire(1);
        if (rSemaphore.tryAcquire(1)) {
            new Thread(() -> {
                try {
                    Thread.sleep(30000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                rSemaphore.release(1);
            }).start();
            return "success";
        } else {
            return "fail";
        }
    }
}
